package factory.one.controller;

import com.alibaba.fastjson2.JSON;
import factory.one.entity.*;
import factory.one.pojo.common.Page;
import factory.one.service.*;
import factory.one.utils.StageUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author sk.z
 * 2023/7/5
 * 订单服务
 **/
@Controller
@RequestMapping("/finance")
public class FinanceController {

    private final OrderService orderService;
    private final BatchService batchService;
    private final CustomService customService;
    private final ProductService productService;
    private final MoneyService moneyService;
    private final CountService countService;

    private final static BigDecimal BD_100 = new BigDecimal(100);

    public FinanceController(OrderService orderService,
                             BatchService batchService,
                             CustomService customService,
                             ProductService productService,
                             MoneyService moneyService,
                             CountService countService) {
        this.orderService = orderService;
        this.batchService = batchService;
        this.customService = customService;
        this.productService = productService;
        this.moneyService = moneyService;
        this.countService = countService;
    }

    @GetMapping("/list.html")
    public String listHtml(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer size,
                           Model model) {
        List<Order> list = orderService.list(page, size);
        trans(list);
        model.addAttribute("page", new Page<>(list, orderService.listCount(), page, size));
        return "finance/list";
    }

    @GetMapping("/detail.html")
    public String detailHtml(@RequestParam Long orderId, Model model) {
        Order order = orderService.getById(orderId);
        Custom custom = customService.getById(order.getCustomId());
        order.setCustomName(custom.getName());
        model.addAttribute("order", order);

        List<Batch> batchList = batchService.list(orderId);
        transBatch(batchList);
        model.addAttribute("batchList", batchList);
        return "finance/detail";
    }

    @GetMapping("/edit.html")
    public String editHtml(@RequestParam Long orderId, Model model) {
        Order order = orderService.getById(orderId);
        Custom custom = customService.getById(order.getCustomId());
        order.setCustomName(custom.getName());
        model.addAttribute("order", order);
        model.addAttribute("batchList", transBatch(batchService.list(orderId)));
        return "finance/edit";
    }

    @ResponseBody
    @PostMapping("/edit")
    @Transactional
    public String edit(@RequestParam Long id,
                       @RequestParam String batchJson) {
        if (StringUtils.hasText(batchJson)) {
            List<Batch> batches = JSON.parseArray(batchJson, Batch.class);
            batchService.updatePrice(batches);
        }
        return "ture";
    }

    @GetMapping("/money.html")
    public String moneyHtml(@RequestParam Long orderId, Model model) {
        List<Money> moneyList = moneyService.listByOrder(orderId);

        int in = 0;
        int out = 0;
        for (Money m : moneyList) {
            switch (m.getType()) {
                case 1:
                    in += m.getAmount();
                    break;
                case 2:
                    out += m.getAmount();
                    break;
            }
        }

        model.addAttribute("orderId", orderId);
        model.addAttribute("moneyList", moneyList);
        model.addAttribute("in", in);
        model.addAttribute("out", out);
        model.addAttribute("contractAmount", orderService.getById(orderId).getContractAmount());
        return "finance/money";
    }

    @ResponseBody
    @PostMapping("/addMoney")
    public String addMoney(Money money) {
        money.setAmount(money.getAmountTmp().multiply(BD_100).longValue());
        money.setCreateUser(SecurityContextHolder.getContext().getAuthentication().getName());
        money.setCreateTime(new Date());
        Long id = moneyService.add(money);
        countService.submitForAmount(money.getOrderId());
        return Long.toString(id);
    }

    private void trans(List<Order> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (Order order : list) {
            Custom custom = customService.getById(order.getCustomId());
            order.setCustomName(custom.getName());
//            StageUtil.build(order);
        }
    }

    private List<Batch> transBatch(List<Batch> list) {
        if (!CollectionUtils.isEmpty(list)) {
            for (Batch batch : list) {
                Product product = productService.getById(batch.getProductId());
                batch.setProductName(product.getName());
                batch.setAmount(batch.getSendNum() * batch.getPrice());
                batch.setProduceGap(Math.max(0, batch.getOrderNum() - batch.getProduceNum()));
                batch.setSendGap(Math.max(0, batch.getOrderNum() - batch.getSendNum()));
            }
        }
        return list;
    }
}